#include "ffvencoderthread.h"
#include"queue/ffvframequeue.h"
#include"queue/ffvpacketqueue.h"
#include"encoder/ffvencoder.h"
#include"muxer/ffmuxer.h"
#include"decoder/ffvdecoder.h"

FFVEncoderThread::FFVEncoderThread()
{

}

FFVEncoderThread::~FFVEncoderThread()
{
    if(vPars){
        delete vPars;
        vPars = nullptr;
    }
}

void FFVEncoderThread::init(FFVEncoder *vEncoder_,FFMuxer *muxer_, FFVDecoder*vDecoder_,FFVFrameQueue *frmQueue_)
{
    vEncoder = vEncoder_;
    muxer = muxer_;
    vDecoder = vDecoder_;
    frmQueue = frmQueue_;
}

void FFVEncoderThread::run()
{
    int64_t firstFramePts = 0;  // 用于存储第一帧的绝对PTS
    bool firstFrame = true;    // 标记是否为第一帧

    while(!m_stop){
        AVFrame* frame = frmQueue->dequeue();
        if(frame == nullptr){
            m_stop = true;
            break;
        }
        if(vPars == nullptr){
            initEncoder(frame);
        }

        if(firstFrame){
            firstFramePts = frame->pts;  // 记录第一帧的绝对PTS
            firstFrame = false;

            // 第一帧的相对PTS为0
            vEncoder->encode(frame, streamIndex, 0,cameraTimeBase);
        }
        else{
            // 计算当前帧的相对PTS
            int64_t relativePts = frame->pts - firstFramePts;
            vEncoder->encode(frame, streamIndex, relativePts,  cameraTimeBase);
        }

//        std::cerr << "relativePTS: " << (firstFrame? 0 : frame->pts - firstFramePts) << std::endl;

        av_frame_unref(frame);
        av_frame_free(&frame);
    }
}
void FFVEncoderThread::initEncoder(AVFrame*frame)
{
    vPars = new FFVideoPars();
    FFVideoPars* tmpPars = vDecoder->getVideoPars(); //解码帧的数据
    memcpy(vPars,tmpPars,sizeof(FFVideoPars));
    cameraTimeBase = vPars->timeBase;

    vEncoder->initVideo(frame,vPars->frameRate);
    muxer->addStream(vEncoder->getCodecCtx());
    streamIndex = muxer->getVStreamIndex();
}
